package com.itmk.web.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.goods.entity.*;
import com.itmk.web.goods.service.GoodsService;
import com.itmk.web.order.entity.OrderListParm;
import com.itmk.web.order.entity.OrderVo;
import com.itmk.web.user.entity.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    //   新增发布商品
    @PostMapping("/publish")
    public ResultVo publish(@RequestBody Goods goods) {
//        设置发布时间
        goods.setCreatedAt(new Date());
        if (goodsService.save(goods)) {
            return ResultUtils.success("publish success");
        }
        return ResultUtils.error("publish error");

    }

    //    列表查询商品数据
    @GetMapping("getList")
    public ResultVo getGoodsList(GoodsListParm goodsListParm) {
        IPage<Goods> page = new Page<>(goodsListParm.getCurrentPage(), goodsListParm.getPageSize());
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(StringUtils.isNotEmpty(goodsListParm.getGoodsName()), Goods::getGoodsName, goodsListParm.getGoodsName()).orderByDesc(Goods::getCreatedAt);
        IPage<Goods> list = goodsService.page(page, queryWrapper);

        return ResultUtils.success("get list success", list);
    }

    // 上架商品
    @PostMapping("/onShelf/{goodsId}")
    public ResultVo onShelf(@PathVariable Integer goodsId) {
        Goods goods = goodsService.getById(goodsId);
        if (goods != null) {
            goods.setStatus(1); // 1 表示上架
            goods.setUpdatedAt(new Date());
            if (goodsService.updateById(goods)) {
                return ResultUtils.success("上架成功");
            }
        }
        return ResultUtils.error("上架失败，商品不存在");
    }

    // 下架商品
    @PostMapping("/offShelf/{goodsId}")
    public ResultVo offShelf(@PathVariable Integer goodsId) {
        Goods goods = goodsService.getById(goodsId);
        if (goods != null) {
            goods.setStatus(0); // 0 表示下架
            goods.setUpdatedAt(new Date());
            if (goodsService.updateById(goods)) {
                return ResultUtils.success("下架成功");
            }
        }
        return ResultUtils.error("下架失败，商品不存在");
    }

    //    编辑
    @PutMapping("/edit")
    public ResultVo edit(@RequestBody Goods goods) {
        if (goodsService.updateById(goods)) {
            return ResultUtils.success("edit success");
        } else {
            return ResultUtils.error("edit error");
        }
    }

    //    删除 ,通过id删除
    @DeleteMapping("/{goodsId}")
    public ResultVo del(@PathVariable("goodsId") int goodsId) {
        if (goodsService.removeById(goodsId)) {
            return ResultUtils.success("delete success");
        } else {
            return ResultUtils.error("delete error");
        }
    }

    // 小程序首页瀑布流
    @GetMapping("/getWaterfallList")
    public ResultVo getWaterfallList(WaterfallListParm parm) {
        IPage<Goods> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());
        QueryWrapper<Goods> query = new QueryWrapper<>();
        query.lambda().eq(Goods::getStatus, 1) // 只显示已上架商品
                .orderByDesc(Goods::getUpdatedAt, Goods::getCreatedAt); // 同时按两个字段排序


        IPage<Goods> list = goodsService.page(page, query);
        return ResultUtils.success("获取瀑布流成功", list);
    }

    // 搜索
    @GetMapping("/search")
    public ResultVo searchGoods(GoodsSearchParm parm) {
        IPage<Goods> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());
        QueryWrapper<Goods> query = new QueryWrapper<>();

        // 只查询已上架商品
        query.lambda().eq(Goods::getStatus, 1);

        // 商品名称搜索
        if (StringUtils.isNotEmpty(parm.getKeyword())) {
            query.lambda().like(Goods::getGoodsName, parm.getKeyword());
        }

        // 排序条件
        switch (parm.getSortType()) {
            case "price":
                query.lambda().orderBy(true, "asc".equals(parm.getSortOrder()), Goods::getPrice);
                break;
            case "update":
                query.lambda().orderByDesc(Goods::getUpdatedAt);
                break;
            case "create":
                query.lambda().orderByAsc(Goods::getCreatedAt);
                break;
            case "userLevel":
                // 假设你有一个getUserLevel方法关联用户等级
                // query.lambda().orderByDesc(Goods::getUserLevel);
                break;
            default:
                query.lambda().orderByDesc(Goods::getCreatedAt);
        }

        IPage<Goods> list = goodsService.page(page, query);
        return ResultUtils.success("搜索成功", list);
    }

    // 闲置页面根据商品分类生成瀑布流
    @GetMapping("/getGoodsByCategory")
    public ResultVo getGoodsByCategory(WaterfallListParm parm) {
        IPage<Goods> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());
        QueryWrapper<Goods> query = new QueryWrapper<>();

        query.lambda().eq(Goods::getStatus, 1).eq(parm.getCategoryId() != null && parm.getCategoryId() != 0, Goods::getCategoryId, parm.getCategoryId()).orderByDesc(Goods::getCreatedAt);

        IPage<Goods> list = goodsService.page(page, query);
        return ResultUtils.success("查询成功", list);
    }
    //    生成上架商品瀑布流
    @GetMapping("/getMyList")
    public ResultVo getMyList(WaterfallListParm parm) {
        QueryWrapper<Goods> query = new QueryWrapper<>();
//构造查询条件，只查询当前用户发布的上架商品
        query.lambda().eq(Goods::getUserId, parm.getUserId())

                .orderByDesc(Goods::getUpdatedAt, Goods::getCreatedAt); // 同时按两个字段排序
        IPage<Goods> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());

        IPage<Goods> list = goodsService.page(page, query);
        return ResultUtils.success("查询成功", list);
    }

    //    生成上架商品瀑布流
    @GetMapping("/getMyPublishedList")
    public ResultVo getMyPublishedList(WaterfallListParm parm) {
        QueryWrapper<Goods> query = new QueryWrapper<>();
//构造查询条件，只查询当前用户发布的上架商品
        query.lambda().eq(Goods::getUserId, parm.getUserId())
                .eq(Goods::getStatus, 1)
                .orderByDesc(Goods::getUpdatedAt, Goods::getCreatedAt); // 同时按两个字段排序
        IPage<Goods> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());

        IPage<Goods> list = goodsService.page(page, query);
        return ResultUtils.success("查询成功", list);
    }

    //    生成下架商品瀑布流
    @GetMapping("/getMySalesList")
    public ResultVo getMySalesList(WaterfallListParm parm) {
        QueryWrapper<Goods> query = new QueryWrapper<>();
//构造查询条件，只查询当前用户发布的上架商品
        query.lambda().eq(Goods::getUserId, parm.getUserId())
                .eq(Goods::getStatus, 0)
                .orderByDesc(Goods::getUpdatedAt, Goods::getCreatedAt); // 同时按两个字段排序
        IPage<Goods> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());

        IPage<Goods> list = goodsService.page(page, query);
        return ResultUtils.success("查询成功", list);
    }

    // 获取最近七天发布商品数量
    @GetMapping("/getRecentGoodsCount")
    public ResultVo getRecentGoodsCount() {
        // 获取最近七天的日期
        Date sevenDaysAgo = new Date(System.currentTimeMillis() - 7L * 24 * 60 * 60 * 1000);
        // 查询最近七天发布的商品数量
        int count = goodsService.count(new QueryWrapper<Goods>().ge("created_at", sevenDaysAgo));
        return ResultUtils.success("获取最近七天商品数量成功", count);
    }

}
